# -*- coding: utf-8 -*-

from mongoengine.django.auth import User

from forms import RegisterForm
from utils import __make_avatar

from people.models import People

def _handle_register(request):
    """
    Handle database related subject for register view 
    """
    #if request.FILES:
    #    print('has file')
    #    form = RegisterForm(request.POST, request.FILES)
    #else:
    print('no file')
    form = RegisterForm(request.POST)

    if not form.is_valid():
        print(form)
        print('form is not valid')
        return False
    else:
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        print(username)
        print(password)
        user = User.create_user(
                  username=username
                , password=password
                )

        if 'email' in form.cleaned_data:
            user.email = form.cleaned_data['email']
            print(user.email)
        
        user.save()

        people = People(user=user)

        #if 'avatar' in request.FILES:
        #    raw_file = request.FILES['avatar']
        #    people.avatar = __make_avatar(raw_file, password)

        try:
            people.save()
        except Exception:
            print(Exception.args)
            return False
        else:
            request.session['homeLatitude'] = form.cleaned_data['latitude']
            request.session['homeLongitude'] = form.cleaned_data['longitude']
            return True


def _handle_validate(request):
    """
    handle database related subject for validate view
    """
    request.encoding = 'utf-8'
    username = request.GET['username']
    try:
        User.objects.get(username=username)
    except Exception:  #DoseNotExist:
        return False
    else:
        return True
